package com.aitaoxue.palx.util;

import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class GsonUtil {

	private static Gson gson = null;
	static {
		if (gson == null) {
			gson = new Gson();
		}
	}

	private GsonUtil() {
	}

	// 转换成json
	public static String GsonString(Object object) {
		String gsonString = null;
		if (gson != null) {
			gsonString = gson.toJson(object);
		}
		return gsonString;
	}

	// 转换成bean
	public static <T> T GsonToBean(String gsonString, Class<T> cls) {
		T t = null;
		if (gson != null) {
			try {
				t = gson.fromJson(gsonString, cls);
			} catch (Exception e) {
				System.out.println("hehe");
			}
		}
		return t;
	}

	// 转换成list
	// 这里看完泛型再改
	// public static <T> List<T> GsonToList(String gsonString, Class<T> cls) {
	// List<T> list = null;
	// if (gson != null) {
	// list = gson.fromJson(gsonString, new TypeToken<List<T>>() {
	// }.getType());
	// }
	// return list;
	// }

	public static <T> List<T> GsonToList(String gsonString, Type type) {
		List<T> list = null;
		if (gson != null) {
			list = gson.fromJson(gsonString, type);
		}
		return list;
	}

	// 转换成list中有map的
	public static <T> List<Map<String, T>> GsonToListMaps(String gsonString) {
		List<Map<String, T>> list = null;
		if (gson != null) {
			list = gson.fromJson(gsonString,
					new TypeToken<List<Map<String, T>>>() {
					}.getType());
		}
		return list;
	}

	// 转换成map
	public static <T> Map<String, T> GsonToMaps(String gsonString) {
		Map<String, T> map = null;
		if (gson != null) {
			map = gson.fromJson(gsonString, new TypeToken<Map<String, T>>() {
			}.getType());
		}
		return map;
	}
	
	//List转化为json
	public static <T> String ListToJson(List<T> list){
		if(gson!=null){
			return gson.toJson(list);
		}
		return null;
	}

}
